package com.hibase.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenfeng
 * @version 1.0
 * @date 2021/6/10 14:05
 * @des https://gitee.com/cheershi
 */
public class EntityUtil {
    /**
     * 实体转换
     *
     * @param source      源对象
     * @param targetClass 目标对象的Class类型
     * @return
     */
    public static <S, T> T transform(S source, Class<? extends T> targetClass) {
        if (!ObjectUtil.isNull(source)) {
            T target = null;
            try {
                target = targetClass.newInstance();
                BeanUtil.copyProperties(source, target);
            } catch (Exception e) {
                return null;
            }
            return target;
        } else {
            return null;
        }
    }

    /**
     * 实体列表转换
     *
     * @param sourceList
     * @param targetClass
     * @return
     */
    public static <S, T> List<T> transform(List<S> sourceList, Class<? extends T> targetClass) {
        List<T> result = new ArrayList<T>();
        if (!ObjectUtil.isNull(sourceList)) {
            for (S source : sourceList) {
                result.add(transform(source, targetClass));
            }
        }
        return result;
    }

    /**
     * 实体转换以json方式转换
     *
     * @param source      源对象
     * @param targetClass 目标对象的Class类型
     * @return
     */
    public static <S, T> T transformByJson(S source, Class<? extends T> targetClass) {
        if (!ObjectUtil.isNull(source)) {
            T target = null;
            try {
                String sourceJson = JSON.toJSONString(source);
                target = JSON.parseObject(sourceJson, targetClass);
            } catch (Exception e) {
                return null;
            }
            return target;
        } else {
            return null;
        }
    }


    /**
     * 实体列表转换
     *
     * @param sourceList
     * @param targetClass
     * @return
     */
    public static <S, T> List<T> transformByJson(List<S> sourceList, Class<? extends T> targetClass) {
        List<T> result = new ArrayList<T>();
        if (!ObjectUtil.isNull(sourceList)) {
            for (S source : sourceList) {
                result.add(transformByJson(source, targetClass));
            }
        }
        return result;
    }
}
